package com.example.txttoxls;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Provider;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import android.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemProperties;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private Button ft_btn;
	private ProgressBar mProgressBar;
	private String filePath = getSDPath() + "/TestReport/";
	private String fileName;
	private XlsOperate xls = new XlsOperate(filePath,fileName);;
	private File dir;
	private File ft_template;//功能测试模板
	private File currentTestReport;
	private String version;
	private String testReportName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		

		version = SystemProperties.get("ro.gn.extvernumber");
//		version = "WBWX192NM_0101_V5388";
		
		ft_btn = (Button) findViewById(R.id.button1);
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		
		dir = new File(getSDPath() + "/TestReport");//创建文件夹对象
		
		//如果没有文件夹，创建文件夹
		if(!dir.exists()){
			dir.mkdirs();
		}
		ft_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				fileName = "ft_testReport";
				
				ft_template = new File(getSDPath() + "/TestReport/ft_testReport.xls");//FT测试模板
				testReportName = version + "_TestReport.xls";
				currentTestReport = new File(getSDPath() + "/TestReport/" + testReportName);
				//如果没有模板也没有生成的测试报告，则拷贝模板
				if(!ft_template.exists() && !currentTestReport.exists()){
					getReportTemplate("ft_testReport");
				}

				//检查数据源
				if(fileIsExists(getSDPath() + "/TestReport/taskSummary.txt")
						&& fileIsExists(getSDPath() + "/TestReport/ft_testCase.xls")
						&& fileIsExists(getSDPath() + "/TestReport/ft_testReport.xls")){
					if(!currentTestReport.exists()){//修改这里的条件判断是否生成报告
//						new creatTestReport().execute("ft_testReport");//向ft_testReport异步写入数据
						xls.setSheets(xls.ReadTxtFile(filePath + "taskSummary.txt"));
					}else{
						Toast.makeText(MainActivity.this, "测试报告已经存在", Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(MainActivity.this, "缺少生成报告的数据文件", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		
		
	}
	
	class creatTestReport extends AsyncTask<String, Integer, String>{
	/**AsyncTask的3个参数：
	 * 第一个是doInBackground的传入参数类型
	 * 第二个是onProgressUpdate的传入参数类型
	 * 第三个是doInBackground的返回值类型，此返回值是onPostExecute的传入参数
	 */
		@Override
		protected void onPreExecute () {//在 doInBackground(Params...)之前被调用，在ui线程执行  
            mProgressBar.setProgress(0);//进度条复位 
            Toast.makeText(MainActivity.this, "开始生成报告", Toast.LENGTH_SHORT).show();
            mProgressBar.setVisibility(View.VISIBLE);
            mProgressBar.setIndeterminate(true);//设置为不可控进度条
            Log.i("YANG", "onPreExecute");
        } 
		
		protected String doInBackground(String... params) {//处理后台执行的任务，在后台线程执行
			// TODO Auto-generated method stub
			publishProgress(0);//将会调用onProgressUpdate(Integer... progress)方法

			ArrayList<String> taskSummarys = xls.ReadTxtFile(filePath + "taskSummary.txt");
			ArrayList<String> caseInfos = xls.getCaseInfo(taskSummarys);
			ArrayList<String> sheetNames = xls.getSheetNames(caseInfos);

			xls.setSheets(sheetNames);
			Log.i("YANG", "doInBackground");
//			xls.setHeader(sheetNames);
//			xls.fillCaseAndResult(caseInfos);
			//重命名文件
//			String version = "WBWX192NM_0101_V5388";
//			new File(getSDPath() + "/TestReport/" + params[0] + ".xls")
//				.renameTo(new File(getSDPath() + "/TestReport/" + testReportName));

			publishProgress(100);
			return null;
		}
		
		protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用，在ui线程执行  
            mProgressBar.setProgress(progress[0]);//更新进度条的进度  
         } 
		
		protected void onPostExecute(String result) {//后台任务执行完之后被调用，在ui线程执行  
            Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT).show(); 
            mProgressBar.setVisibility(View.GONE);
		}
		
		protected void onCancelled () {//在ui线程执行，只有cancel方法可以调用 
            mProgressBar.setProgress(0);//进度条复位  
        } 
	}

	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
//		new Environment().isExternalStorageRemovable();
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();
		}
		return sdDir.toString();
	}
	
	public boolean fileIsExists(String path){
		File f = new File(path);
		if(!f.exists()){
			return false;
        }else{
        	return true;
        }
	}
	
	public void getReportTemplate(String templateName){
		 try {
			InputStream inputStream = getAssets().open(templateName + ".xls");
			FileOutputStream fos =new FileOutputStream(getSDPath() + "/TestReport/" + templateName + ".xls");
			int count =0;
			byte[] buffer = new byte[1024];
			while ((count = inputStream.read(buffer)) > 0){
				fos.write(buffer, 0, count); 
           }  
			fos.close();
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
